#include "stdafx.h"
#include "WindowsApplication.h"
#include "SystemInformation.h"
#include "Window.h"
#include "HCM/ComponentRegistry.h"

using namespace Hiranipra;
using namespace Hiranipra::HCM;
using namespace Hiranipra::Platform;

// {0C94B1E0-1579-4280-A137-3246F3F535CD}
DEFINE_HCMID( implId ) = { 0xc94b1e0, 0x1579, 0x4280, { 0xa1, 0x37, 0x32, 0x46, 0xf3, 0xf5, 0x35, 0xcd } };
REGISTER_COMPONENT_IMPL( Hiranipra::Platform::IApplication, WindowsApplication, implId );

WindowsApplication::WindowsApplication()
{
	_systemInfo = new SystemInformation();

	LARGE_INTEGER frequency;
	bool gotTiming = ( QueryPerformanceFrequency( &frequency ) == TRUE );
	ASSERT( gotTiming, "Unable to get timing information" );
	_timeFrequency = frequency.QuadPart;

	LARGE_INTEGER time1, time2;
	QueryPerformanceCounter( &time1 );
	QueryPerformanceCounter( &time2 );
	_timeOverhead = time2.QuadPart - time1.QuadPart;
	_timeLast = 0;
}

WindowsApplication::~WindowsApplication()
{
	RELEASE( _systemInfo );
}

ISystemInformation* WindowsApplication::QuerySystemInformation() const
{
	return _systemInfo;
}

IWindow* WindowsApplication::NewWindow( const WindowParameters& params )
{
	return new Window( params );
}

uint64 WindowsApplication::GetTimeFrequency() const
{
	return _timeFrequency;
}

uint64 WindowsApplication::GetTimeElapsed()
{
	LARGE_INTEGER current;
	QueryPerformanceCounter( &current );
	if( _timeLast == 0 )
	{
		_timeLast = current.QuadPart;
		return 1;
	}
	uint64 delta = current.QuadPart - _timeLast - _timeOverhead;
	_timeLast = current.QuadPart;
	if( delta == 0 )
		return 1;
	return delta;
}

bool WindowsApplication::Update()
{
	MSG msg;
	if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
    {
        TranslateMessage( &msg );
        DispatchMessage( &msg );
    }
	return true;
}
